import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Button,
  Timeline,
  message,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { TextArea } = Input;
const { Item } = Form;

interface ShelvesToHeapAddProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: any;
  INITINFO: any;
  location: { query: any };
}

@connect(({
  shelvesToHeapAdd: { detailInfo },
  common: { INITINFO },
}: any) => ({
  detailInfo,
  INITINFO,
}))

class ShelvesToHeapAddElem extends Component<ShelvesToHeapAddProps> {
  componentDidMount() {
    const { location: { query: { id } } } = this.props;
    if (id) this.fetchDetailInfo(id);

    this.fetchAction('common/fetchTariffList');
    this.fetchAction('common/fetchLogisList');
  }

  componentDidUpdate(props: any) {
    const { location: { query: { id } } } = this.props;
    if (id && id !== props.location.query.id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'shelvesToHeapAdd/fetch',
      payload: { id },
    });
  };

  handleSubmit = () => {
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { longitude, latitude } = values;
      if (longitude.length > 16 || Number(longitude) < -180 || Number(longitude) > 180) {
        message.error('经度输入不正确');
        return;
      }
      if (latitude.length > 16 || Number(latitude) < -90 || Number(latitude) > 90) {
        message.error('纬度输入不正确');
        return;
      }

      const params = { ...values };
      const { location: { query } } = this.props;
      if (query) params.id = query.id;
      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `shelvesToHeapAdd/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const {
      detailInfo,
      INITINFO: { tariffList, logisList },
      form: { getFieldDecorator },
    } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Form hideRequiredMark className="tableListForm">
          <Card bordered={false} title="基本信息">
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="货架/地堆编号" colon={false}>
                  {getFieldDecorator('code', {
                    initialValue: detailInfo.code,
                  })(
                    <Input disabled placeholder="保存时编号自动生成" />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　状态" colon={false}>
                  {getFieldDecorator('status', {
                    initialValue: detailInfo.status || 1,
                    rules: [{ required: true, message: '请选择状态' }],
                  })(
                    <Select placeholder="请选择">
                      <Option value={0}>禁用</Option>
                      <Option value={1}>调试</Option>
                      <Option value={2}>上线</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　收费套餐" colon={false}>
                  {getFieldDecorator('tariffpkgId', {
                    initialValue: detailInfo.tariffpkgId || 0,
                    rules: [{ required: true, message: '请选择收费套餐' }],
                  })(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      <Option value={0}>无</Option>
                      {tariffList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="货架/地堆名称" colon={false}>
                  {getFieldDecorator('name', {
                    initialValue: detailInfo.name,
                    rules: [{ required: true, message: '请输入货架/地堆名称' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　类型" colon={false}>
                  {getFieldDecorator('type', {
                    initialValue: detailInfo.type || 0,
                    rules: [{ required: true, message: '请选择类型' }],
                  })(
                    <Select>
                      <Option value={0}>地堆</Option>
                      <Option value={1}>货架</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　物流中心" colon={false}>
                  {getFieldDecorator('logisId', {
                    initialValue: detailInfo.logisId,
                    rules: [{ required: true, message: '请选择物流中心' }],
                  })(
                    <Select
                      showSearch
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="货架/地堆地址" colon={false}>
                  {getFieldDecorator('addr', {
                    initialValue: detailInfo.addr,
                    rules: [{ required: true, message: '请输入货架/地堆地址' }],
                  })(
                    <TextArea placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　经度" colon={false}>
                  {getFieldDecorator('longitude', {
                    initialValue: detailInfo.longitude,
                    rules: [{ required: true, message: '请输入经度' }],
                  })(
                    <Input allowClear type="number" step={0.00000000000001} placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="　　　　纬度" colon={false}>
                  {getFieldDecorator('latitude', {
                    initialValue: detailInfo.latitude,
                    rules: [{ required: true, message: '请输入纬度' }],
                  })(
                    <Input allowClear type="number" step={0.00000000000001} placeholder="请输入" />,
                  )}
                </Item>
              </Col>
            </Row>
          </Card>

          {detailInfo.id && (
            <Card bordered={false} title="日志信息" style={{ marginBottom: -40 }}>
              <Timeline>
                <Timeline.Item>最近操作人：{detailInfo.updateUserName || '--'}</Timeline.Item>
                <Timeline.Item>最近操作时间：{detailInfo.updateTime}</Timeline.Item>
                <Timeline.Item>创建人：{detailInfo.createUserName || '--'}</Timeline.Item>
                <Timeline.Item>创建时间：{detailInfo.createTime}</Timeline.Item>
              </Timeline>
            </Card>
          )}

          <Card bordered={false} style={{ marginTop: -20 }}>
            <Button
              type="primary"
              onClick={this.handleSubmit}
            >
              保存
            </Button>
            <Button
              ghost
              type="primary"
              className="marginL16"
              onClick={() => router.goBack()}
            >
              取消
            </Button>
          </Card>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<ShelvesToHeapAddProps>()(ShelvesToHeapAddElem);
